package com.example.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Admin;
import com.example.entity.Log;
import com.example.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private LogService logService;

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint,AutoLog autoLog) throws Throwable {

        // 操作内容
        String name = autoLog.value();
        // 操作时间
        String time = DateUtil.now();
        // 操作人
        String username = "";
        Admin user = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isNotEmpty(user)){
            username = user.getName();
        }
        // 操作ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();


        // 执行方法
        Result result = (Result) joinPoint.proceed(); // 执行controller中的方法，返回类型是那个接口的返回类型Result


        //登录接口没有日志的原因是放开了登录接口，那么就不会记录token信息，而登录接口调用成功之后回返回Admin信息，因此利用好，而不是利用jwttoken
        Object data = result.getData();
        if (data instanceof Admin){
            Admin admin = (Admin) data;
            username = admin.getName();
        }

        // 保存日志
        Log log = new Log(null, time, ip, username, name);
        logService.save(log);

        return result;
    }
}
